package com.qms.qep.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

/**
 * PDF生成工具类
 * 
 * @author qms
 */
@Component
public class PdfGeneratorUtil {
    
    private static final Logger log = LoggerFactory.getLogger(PdfGeneratorUtil.class);
    
    @Value("${qms.profile}")
    private String uploadPath;
    
    private boolean fontAvailable = false;
    private String fontPath = "static/fonts/simsun.ttc";
    
    @PostConstruct
    public void init() {
        try {
            ensureFontExists();
        } catch (IOException e) {
            log.error("初始化字体目录失败", e);
        }
    }
    
    /**
     * 生成PDF文件
     * 
     * @param htmlContent HTML内容
     * @param fileName 文件名
     * @return 生成的PDF文件路径
     * @throws IOException IO异常
     * @throws DocumentException 文档异常
     */
    public String generatePdf(String htmlContent, String fileName) throws IOException, DocumentException {
        // 创建目录
        String pdfPath = uploadPath + "/certificate/pdf";
        Path path = Paths.get(pdfPath);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        
        // 完整文件路径
        String fullPath = pdfPath + "/" + fileName;
        
        // 生成PDF
        try (OutputStream os = new FileOutputStream(fullPath)) {
            ITextRenderer renderer = new ITextRenderer();
            
            // 添加中文字体支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            if (fontAvailable) {
                fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            
            // 处理HTML内容
            String xhtml = convertToXhtml(htmlContent);
            
            renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(os);
        }
        
        return "/profile/certificate/pdf/" + fileName;
    }
    
    /**
     * 生成PDF字节数组
     * 
     * @param htmlContent HTML内容
     * @return PDF字节数组
     * @throws IOException IO异常
     * @throws DocumentException 文档异常
     */
    public byte[] generatePdfBytes(String htmlContent) throws IOException, DocumentException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ITextRenderer renderer = new ITextRenderer();
            
            // 添加中文字体支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            if (fontAvailable) {
                fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            
            // 处理HTML内容
            String xhtml = convertToXhtml(htmlContent);
            
            renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(baos);
            
            return baos.toByteArray();
        }
    }
    
    /**
     * 将HTML转换为XHTML
     * 
     * @param html HTML内容
     * @return XHTML内容
     */
    private String convertToXhtml(String html) {
        // 添加必要的HTML头部和CSS样式
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        sb.append("<head>");
        sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        sb.append("<style type=\"text/css\">");
        if (fontAvailable) {
            sb.append("body { font-family: SimSun, sans-serif; }");
        } else {
            sb.append("body { font-family: serif; }");
        }
        sb.append("table { border-collapse: collapse; width: 100%; }");
        sb.append("table, th, td { border: 1px solid black; }");
        sb.append("th, td { padding: 5px; text-align: left; }");
        sb.append(".certificate-header { text-align: center; font-size: 24px; font-weight: bold; margin: 20px 0; }");
        sb.append(".certificate-content { margin: 20px; line-height: 1.5; }");
        sb.append(".certificate-footer { margin-top: 30px; text-align: right; }");
        sb.append("</style>");
        sb.append("</head>");
        sb.append("<body>");
        
        // 处理HTML内容，确保其符合XHTML规范
        String processedHtml = html.replace("<br>", "<br />");
        processedHtml = processedHtml.replace("<hr>", "<hr />");
        processedHtml = processedHtml.replace("<img ", "<img alt=\"\" ");
        
        sb.append(processedHtml);
        sb.append("</body></html>");
        
        return sb.toString();
    }
    
    /**
     * 确保字体文件存在
     * 
     * @throws IOException IO异常
     */
    public void ensureFontExists() throws IOException {
        String fontDir = "static/fonts";
        Path fontPath = Paths.get(fontDir);
        if (!Files.exists(fontPath)) {
            Files.createDirectories(fontPath);
        }
        
        File simsunFont = new File(this.fontPath);
        if (simsunFont.exists()) {
            fontAvailable = true;
            log.info("找到中文字体文件: {}", this.fontPath);
        } else {
            fontAvailable = false;
            log.warn("中文字体文件不存在，需要手动复制宋体字体文件到 {} 目录", fontDir);
            log.warn("PDF生成将使用默认字体，可能无法正确显示中文");
        }
    }
} 